package com.chuangke.common.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectionUtils {

	@SuppressWarnings("rawtypes")
	public static List<List> splite(List dataList,int splitNum){
		List<List> list = new ArrayList<>() ;
		if(dataList == null || dataList.isEmpty()) {
			return list ;
		}
		if(dataList.size()<=splitNum) {
			list.add(dataList) ;
			return list ;
		}
		
		double splitNumd = splitNum*1.0 ;
		int count = (int) Math.ceil(dataList.size()/splitNumd) ;
		for(int i=0; i<count; i++) {
			int fromIndex = i*splitNum ;
			int toIndex = i*splitNum+splitNum;
			toIndex = Math.min(toIndex, dataList.size());
			list.add(dataList.subList(fromIndex, toIndex));
		}
		
		return list ;
	}
	
	/**
	 * 字符串类型的数值排序
	 * @param o1
	 * @param o2
	 * @return
	 */
	public static int compare(String o1, String o2) {
		if (o1.length() != o2.length()) {
			return o1.length() - o2.length();
		}
		return o1.compareTo(o2);
	}
	
	/**
	 * 将数据分组，根据方法引用（bean的get方法）
	 *
	 * @param list      为分组的数据
	 * @param functions get方法数组
	 */
	@SafeVarargs
	public static <T, R> Map<String, List<T>> groupingBy(List<T> list, Function<T, R>... functions) {
		return list.stream().collect(Collectors.groupingBy(t -> groupingBy(t, functions)));
	}

	/**
	 * 分组工具根据函数式接口使用分组，将数据根据分组结果进行拆分
	 */
	@SafeVarargs
	public static <T, R> String groupingBy(T t, Function<T, R>... functions) {
		if (functions == null || functions.length == 0) {
			throw new NullPointerException("functions数组不可以为空");
		} else if (functions.length == 1) {
			return functions[0].apply(t).toString();
		} else {
			return Arrays.stream(functions).map(fun -> fun.apply(t).toString())
					.reduce((str1, str2) -> str1 + "|" + str2).get();
		}
	}
}
